 package com.ghbank.rdws.management.service.impl;

import java.util.concurrent.ExecutionException;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ghbank.rdws.biz.repository.SysDataSourceConfigRepository;
import com.ghbank.rdws.common.db.DataSourceFactory;
import com.ghbank.rdws.common.db.utils.DbUtils;
import com.ghbank.rdws.common.entity.SysDataSourceConfig;
import com.ghbank.rdws.common.model.DataSourceConfig;
import com.ghbank.rdws.common.model.DbType;
import com.ghbank.rdws.management.service.ConfigService;

@Service
public class ConfigServiceImpl implements ConfigService {
    @Autowired
    private DataSourceFactory dataSourceFactory;
    
    @Autowired
    private SysDataSourceConfigRepository sysDataSourceConfigRepository;
    
    @Override
    public void changeSysDataSource(long id, String url, String username, String password) throws ExecutionException {
        SysDataSourceConfig dataSourceConfig = sysDataSourceConfigRepository.findById(id).get();
        if (dataSourceConfig != null) {
            DbType dbType = DbType.valueOf(dataSourceConfig.getDbType().toUpperCase());
            DataSourceConfig config = DbUtils.getDataSourceConfig(dataSourceConfig,dbType);
            dataSourceFactory.removeDataSource(config);
        }
        if (StringUtils.isNotEmpty(url)) {
            dataSourceConfig.setJdbcUrl(url);
        }
        if (StringUtils.isNotEmpty(username)) {
            dataSourceConfig.setJdbcUsername(username);
        }
        if (StringUtils.isNotEmpty(password)) {
            dataSourceConfig.setJdbcPassword(password);
        }
        sysDataSourceConfigRepository.save(dataSourceConfig);
    }
    
    
}
